import Notify from '../../miniprogram_npm/@vant/weapp/notify/notify';
import Dialog from '../../miniprogram_npm/@vant/weapp/dialog/dialog';
import api from '../../utils/api';

Page({

  /**
   * 页面的初始数据
   */
  data: {
    show:false,
    proNum:0,
    scorenum:0,
    nextText:'下一题',
    prevText:'上一题',
    answerList:[],
    dataTest: [],
    score:[1,2,3,4],
    optionList: [],
    numList:[],
    dxList:[],
    username:'',
    username1:'',
    username2:'',
    zjVal:'',
    movableViewInfo: {
      y: 0,
      showClass: 'none',
      data: {}
    },
    pageInfo: {
      rowHeight: 47,
      scrollHeight: 85,

      startIndex: null,
      scrollY: true,
      readyPlaceIndex: null,
      startY: 0,
      selectedIndex: null,
    },
    testData: [],
    inputValue:'',
    selectId:0,
    quesNum :1
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {

    console.log(options.selectId);
    let _this = this;
    api.get("evaluation/"+options.selectId, {
    }).then(res => {
      console.log(res)
      if(res.data.length > 0){
        let newdata = res.data[this.data.proNum];
        console.log(newdata)
        this.setData({
          dataTest: newdata,
          testData:res.data,
          selectId:options.selectId
        })
      }
    }).catch(err => {
      wx.showToast({
        title: err.msg,
        icon: 'none'
      })
    })
    
  },
  /**
   * 点击选项方法
   */
  selection:function(e){
      this.setData({
        num: e.target.dataset.num,
        show:!this.data.show
      })
    // }
  },
  /**
   * 选择题
   */
  selection2:function(e){
    var str = e.target.dataset.title;
    this.setData({
      num2: e.target.dataset.num2,
      selTitle:str
    })
  },
    /**
   * 多项选择题
   */
  selection3:function(e){
    var str = e.target.dataset.title;
    var num = e.target.dataset.num2;
    if(this.data.numList.length < 3 && this.data.numList.indexOf(num)=='-1'){
        this.data.numList.push(num)
        this.data.dxList.push(str)
    }else{
      this.delList(this.data.numList,num)
      this.delList(this.data.dxList,str)
    }
    this.setData({
      numList: this.data.numList,
      // selTitle:str
    })
    console.log(this.data.dxList)
    console.log(this.data.numList)
  },
  /**
   * 关闭弹窗
   */
  onClose:function(){
    this.setData({
      show:false
    })
  },
  /**
   * 选择分数
   */
  choiceScore:function(e){
    var num = this.data.num-1; //选项下标
    console.log(num)
    var scorenum = e.target.dataset.scorenum; //分数
    var title = this.data.dataTest.item[num].title; //选项
    var oldScore;
    var regex = "\\[(.+?)\\]";
    oldScore = title.match(regex);
    console.log(oldScore);
    this.data.score = this.delList(this.data.score, scorenum)//删除数组中的分数
    
    if (oldScore != null){
      console.log('不是null')
      this.data.dataTest.item[num].title = title.split(" ")[0] + " [" + scorenum + "]";
      this.data.dataTest.item[num].scorenum = parseInt(scorenum);
      this.addList(this.data.score, oldScore[1])
      //获取源数据的下标，改为新数据
      this.spliceList(this.data.answerList,oldScore[1],parseInt(scorenum))
    }else{
      this.data.dataTest.item[num].scorenum =parseInt(scorenum);
      this.data.dataTest.item[num].title = title + " [" + scorenum + "]";
      this.data.answerList.push(parseInt(scorenum)) //添加到结果数组中
    }
    this.setData({
      show: false,
      score: this.data.score,
      dataTest: this.data.testData[this.data.proNum]
    })
    
    //  //选择题答案数组
    // console.log(this.data.answerList)
  },
  /**
   * 切换下一题
   */
  next:function(e){
    var _this = this;
    let proNum = parseInt(e.target.dataset.pronum);
    console.log(proNum+"======");
    // if (proNum <= _this.data.testData.length-1){
    if(_this.data.nextText != '提交'){
      console.log(_this.data.dataTest)
      let quesTypeNo = _this.data.testData[proNum].type
      let quesId = _this.data.testData[proNum].id
      console.log(_this.data.answerList) //判断当提醒为选择题时，4个选项是否都已选择
      if (quesTypeNo==3){ //选择填空题
        let t1 = _this.data.dataTest.item[0].scorenum
        let t2 = _this.data.dataTest.item[1].scorenum
        let t3 = _this.data.dataTest.item[2].scorenum
        let t4 = _this.data.dataTest.item[3].scorenum
        let al = [t1,t2,t3,t4];
        if (_this.data.answerList.length<4){
          Notify({ type: 'warning', message: '请完整选择' });
          return;
        }
        // 评分题答案提交
        _this.postAnswer(_this.data.selectId,quesId,JSON.stringify(al));
        proNum = proNum + 1;
        _this.setData({
          proNum: proNum,
          dataTest: _this.data.testData[proNum],
          score: [1, 2, 3, 4],
          answerList:[]
        })
      }else if(quesTypeNo == 1){//填空题
        let as1 = _this.data.username;
        let as2 = _this.data.username1;
        let as3 = _this.data.username2;
        console.log(as1+"=="+as2+"==="+as3)
        let arr = [];
        if(this.data.dataTest.space == 3){
          arr.push(as1);
          arr.push(as2);
          arr.push(as3);
          if(as1 == ''|| as2==''|| as3==''){
            Notify({ type: 'warning', message: '请完整选择' });
            return ;
          }
        }else if(this.data.dataTest.space == 2){
          arr.push(as1);
          arr.push(as2);
          if(as1 == ''|| as2==''){
            Notify({ type: 'warning', message: '请完整选择' });
            return ;
          }
        }else if(this.data.dataTest.space == 1){
          arr.push(as1);
          if(as1 == ''){
            Notify({ type: 'warning', message: '请完整选择' });
            return ;
          }
        }
        //填空题答案提交
        _this.postAnswer(_this.data.selectId,quesId,JSON.stringify(arr))
        proNum = proNum + 1;
        console.log(_this.data.testData[proNum])
        _this.setData({
          proNum: proNum,
          dataTest: _this.data.testData[proNum],
          inputValue:'',
          username:'',
          username1:'',
          username2:''
        })
      }else if(quesTypeNo == 4){//单项选择题
        let selTitle = _this.data.selTitle;
        let val =_this.data.num2;
        console.log(selTitle)
        if (typeof (selTitle)=='undefined'||selTitle == ''){
          Notify({ type: 'warning', message: '请完整选择' });
          return;
        }
        if(_this.data.selectId == 1 || _this.data.selectId == 2){
          _this.postAnswer(_this.data.selectId,quesId,selTitle);
        }else{
          _this.postAnswer(_this.data.selectId,quesId,val);
        }
        
        proNum = proNum + 1;
        _this.setData({
          proNum: proNum,
          dataTest: _this.data.testData[proNum],
          num2:'',
          selTitle:''
        })
      }else if(quesTypeNo == 5){//造句题
        let zjVal = _this.data.zjVal;
        if(zjVal == ''){
          Notify({ type: 'warning', message: '请完整选择' });
          return ;
        }
        //造句答案提交
        _this.postAnswer(_this.data.selectId,quesId,zjVal)
        proNum = proNum + 1;
        console.log(_this.data.testData[proNum])
        _this.setData({
          proNum: proNum,
          dataTest: _this.data.testData[proNum],
          inputValue:'',
          zjVal:''
        })
      }else if(quesTypeNo == 6){//多项选择题
        let dxList = _this.data.dxList;
        let numList = _this.data.numList;
        if (dxList.length<3){
          Notify({ type: 'warning', message: '请完整选择' });
          return;
        }
        _this.postAnswer(_this.data.selectId,quesId,JSON.stringify(dxList));
        proNum = proNum + 1;
        _this.setData({
          proNum: proNum,
          dataTest: _this.data.testData[proNum],
          dxList:[],
          numList:[]
        })
      }
      // 第一套题
      if(_this.data.selectId==1&&_this.data.quesNum<=4){
        // 调用第一套的接口并传输次数
        if (proNum == _this.data.testData.length) {
          _this.getQuestion(_this.data.selectId,_this.data.quesNum++)
        }
      // 第二套题
      }else if(_this.data.selectId==2&&_this.data.quesNum<=2){
        // 调用为2的接口，并传输次数
        if (proNum == _this.data.testData.length) {
          _this.getQuestion(_this.data.selectId,_this.data.quesNum++)
        }
      }else{
        if (proNum == _this.data.testData.length) {
          _this.setData({
            nextText: '提交'
          })
        }
      }
    }else{
      Dialog.confirm({
        title: '提示',
        message: '请确认是否提交？'
      }).then(() => {
        // on confirm
        console.log('交卷')
        let url="";
        let selectId = _this.data.selectId;
        if(selectId == 1){
          url="../component/pages/smyt/smyt"
        }else if(selectId == 2){
          url="../component/pages/hxjzg/hxjzg"
        }else if(selectId == 3){
          url="../component/pages/mdjzg/mdjzg"
        }else if(selectId == 4){
          url="../component/pages/4p/4p"
        }else if(selectId == 5){
          url="../component/pages/VAKD/VAKD"
        }else if(selectId == 6){
          url="../component/pages/holland/holland"
        }else if(selectId == 7){
          url="../component/pages/MBTI/MBTI"
        }
        wx.redirectTo({
          url: url
        })
      }).catch(() => {
        console.log('取消')
      });
    }
  },
  /**
   * 上一题
   */
  prev:function(e){
    let proNum = parseInt(e.target.dataset.pronum);
    proNum = proNum - 1;
    if (proNum < 0) {
      Notify({ type: 'primary', message: '已是第一题' });
      return;
    }
    this.setData({
      nextText: '下一步',
      proNum: proNum,
      dataTest: this.data.testData[proNum],
      answerList:[]
    })
    this.ct()
  },
  /**
   * 删除数据元素
   * 根据下标
   */
  delList:function(list,id){
    for(var arr in list){
      console.log(arr)
      if(list[arr] == id){
        list.splice(arr, 1)
      }
    }
    // this.data.score = list;
    return list;
  },
  /**
   * 
   * @param {*} list 
   * @param {*} id 
   */
  tkList:function(a1,a2,a3){
    let arr = [];
    arr.push(a1);
    arr.push(a2);
    arr.push(a3);
    return arr;
  },
  /**
   * 增加数组元素
   * 根据数据大小自动冒泡排序
   */
  addList:function(list,id){
    list.push(id);
    return list;
  },
  /**
   * 分数重置
   */
  ct:function(){
    let data = this.data.testData[this.data.proNum].item;
    for (var arr in data) {
      var it = data[arr].title;
      var oldScore;
      var regex = "\\[(.+?)\\]";
      oldScore = it.match(regex);
      if (oldScore != null){
        this.data.testData[this.data.proNum].item[arr].title = this.data.testData[this.data.proNum].item[arr].title.split(" ")[0]
      }
    }
    console.log(data)
    this.setData({
      dataTest: this.data.testData[this.data.proNum],
      answerList:[],
      score: [1, 2, 3, 4]
    })
  },
  /**
   * 获取input值
   */
  getInputValue:function(e){
    let item  = e.currentTarget.dataset.name;
    let title  = e.currentTarget.dataset.title;
    this.setData({
      [item]: title+e.detail.value
    })
  },
  /**
   * 答案提交
   */
  postAnswer:function(_evaluation_id,_question_id,_answer){
    let token = wx.getStorageSync('token');
    api.post("answer", {
      "token":token,
      "evaluation_id":_evaluation_id,
      "question_id":_question_id,
      "answer":_answer,
    }).then(res => {
      console.log(res)
    }).catch(err => {
      wx.showToast({
        title: err.msg,
        icon: 'none'
      })
    })
  },
  /**
   * 获取后续题目
   */
  getQuestion:function(_evaluation_id,_num){
    let token = wx.getStorageSync('token');
    let newNum = 0;
    api.get("completion?token="+token+"&evaluation_id="+_evaluation_id+"&number="+_num, {
    }).then(res => {
      console.log(res)
      if(res.data.length > 0){
        let newdata = res.data[newNum];
        console.log(newdata)
        this.setData({
          dataTest: newdata,
          testData:res.data,
          selectId:_evaluation_id,
          proNum:newNum
        })
      }
    }).catch(err => {
      wx.showToast({
        title: err.msg,
        icon: 'none'
      })
    })
  },
  /**
   * 根据数字获取数组下标并替换
   */
  spliceList:function(_arr,_num,_newNum){
    console.log("原来的值"+_num)
    console.log("新的"+_newNum)
    if(_arr.length > 0){
      for(var i in _arr){
        console.log(_arr)
          if(_arr[i]==_num){
            console.log('有重复的值下标为'+i)
            _arr[i] = _newNum;
          }
      }
    }
  }
})